<?php
//-------------------------------------------------------------------------------------------------------
    require_once($config['app_dir'] . '/includes/object.class.php');
    require_once($config['app_dir'] . '/includes/db.class.php');
    //---------------------------------------------------------------------------------------------------

    class objDBUser extends objDBActiveRecord {
            protected $_table = 'fa_users';
            protected $_key = 'userid';

        public function ClassName() {
            return  __CLASS__;
        } //ClassName

        public function LoadByLogin($aID) {
            $this->Record();
            if( $aID && $this->_key && !$this->isRecordEmpty() )
                $this->_record->Load("Login=$aID");
        } //LoadbyLogin

    } //class DBUser

    //---------------------------------------------------------------------------------------------------

    class objDBSystem extends objDBActiveRecord {
            protected $_table = 'fa_systems';
            protected $_key = 'systemid';

        public function ClassName() {
            return  __CLASS__;
        } //ClassName

    } //class DBSystem

    //---------------------------------------------------------------------------------------------------

    class objDBTrade extends objDBActiveRecord {
            protected $_table = 'fa_trades';
            protected $_key = 'tradeid';

        public function ClassName() {
            return  __CLASS__;
        } //ClassName

    } //class DBTrade

    //---------------------------------------------------------------------------------------------------

    class objDBForecast extends objDBActiveRecord {
            protected $_table = 'fa_forecast';
            protected $_key = 'forecastid';

        public function ClassName() {
            return  __CLASS__;
        } //ClassName

    } //class DBForecast

    //---------------------------------------------------------------------------------------------------

    class objDBMailer_Session extends objDBActiveRecord {
            protected $_table = 'fa_mailer_sessions';
            protected $_key = 'sessionid';

        public function ClassName() {
            return  __CLASS__;
        } //ClassName

        public function Start() {
            return $this->Save();
        } //Get

    } //class DBMailer_Session

    //---------------------------------------------------------------------------------------------------

    class objDBMailer_Mail extends objDBActiveRecord {
            protected $_table = 'fa_mailer_mails';
            protected $_key = 'mailid';

            public $show = false;
            public $cache = false;

        public function ClassName() {
            return  __CLASS__;
        } //ClassName

        public function setID( $aValue )  {
            return $this->_id = $aValue;
        } //setID

        public function BLOB_Update($aID=false, $path=false) {
            $this->_db->handler->UpdateBlobFile($this->_table, 'attachment', $path, "$this->_key=$aID");
        } //BLOB_Update

        public function BLOB_Save2File($aID=false, $path=false, $force=false) {
            if( !$aID && !$path) return false;
            if( $this->_record->{$this->_key} != $aID ) $this->Load($aID);
            if( $force ) {
                if( file_exists($path) ) @unlink($path);
                return file_put_contents($path, $this->_record->attachment);
            } else {
                if( !file_exists($path) ) return file_put_contents($path, $this->_record->attachment);
                else return true;
            }
        } //BLOB_Save2File

        public function Send() {
          global $config;

            if( $this->isEmpty() ) return false;
            //-------------------------------------------------------------------------------------------
            // Load user
            $rUser = new objDBUser();
            $rUser->Load($this->_record->userid);
            if( $rUser->isEmpty() ) return false;
            // /Load user
            //-------------------------------------------------------------------------------------------
            // Save image
            $this->cache = false;
            if( 1==$this->_record->messagetype || 2==$this->_record->messagetype ) {
                $image_filename = $this->_record->imagefilename;
                $image_path = $config['jpgraph']['cache_dir'] . $this->_record->messageid . '-' . $image_filename;

                $this->BLOB_Save2File(false, $image_path );
                $this->cache = $image_path;
            } //if have to be image
            else {
                $image_filename = false;
                $image_path = false;
            }
            // /Save image
            //-------------------------------------------------------------------------------------------
            // Mailer
            if( $this->show ) echo $rUser->login .' ';
            $Mailer = new objMailer();
            $Mailer->SMTPKeepAlive = true;
            $Mailer->isHTML($this->_record->ishtml);
            switch( $this->_record->messagetype ) {
                case 1:
                    if( $image_path ) $Mailer->AddEmbeddedImage($image_path, $image_filename, $image_filename);
                break;
                //----------------------------------------------------------
                case 2:
                    if( $image_path ) $Mailer->AddAttachment($image_path, $image_filename);
                break;
            } //switch
            $Mailer->Subject = $this->_record->subject;
            $Mailer->Body = $this->_record->body;

            if( 5==$this->_record->messagetype)
                $Mailer->AddAddress('sms@messaging.clickatell.com');
            elseif( 3==$this->_record->messagetype ) {
                $Mailer->AddAddress($rUser->smsaddress);
            }
            else
                $Mailer->AddAddress($rUser->login, $rUser->name);

            $code = $Mailer->Send();

            $result = $Mailer->Message;
            $result['result'] = $Mailer->ErrorInfo;
            $result['code'] = $Mailer->isError();

            $Mailer->ClearAddresses();
            $Mailer->SmtpClose();
            // /Mailer
            //-------------------------------------------------------------------------------------------
            // Update statistics
            $Status = new objDBMailer_Status();
            $Status->mailid = $this->_record->mailid;
            $Status->statusid = intval($result['code']);
            $Status->description = $result['result'];
            $Status->Insert();

            $this->_record->statusid = $Status->statusid;
            $this->_record->statusdate = $Status->date;
            $this->_record->tries += 1;
            $this->_record->Update();
            // /Update statistics
            //-------------------------------------------------------------------------------------------
            return $result;
        } //Send

    }//class DBMailer_Mail

    //---------------------------------------------------------------------------------------------------

    class objDBMailer_Status extends objDBActiveRecord {

            protected $_table = 'fa_mailer_status';

            protected $_mail_id = false;
            protected $_status_id = false;

        public function ClassName() {
            return  __CLASS__;
        }//ClassName
/*
        public function __set($aName, $aValue) {
            parent::__set($aName, $aValue);

            switch( strlower($aName) ) {
                case 'mail':
                case 'mailid':
                case 'mail_id':
                    $this->_mail_id = $aValue;
                    $this->_sqls();
                    $this->Record();
                break;
                //-------------------------------------------------------------
                case 'status':
                case 'statusid':
                case 'status_id':
                    $this->_status = $aValue;
                    $this->_sqls();
                    $this->Record();
                break;
                //-------------------------------------------------------------
            } //switch

        } //setter

        public function Update() {
            if( !$this->isEmpty() ) {
                //$this->_record->Load( $this->BuildWhere() );
                $this->_record->description = $this->_description;
                $this->_record->statusid = $this->_status_id;
                $this->_record->mailid = $this->_mail_id;
                $this->_record->Save();
            } //if parameters are not empty
        } //Update

        public function isEmpty() {
            return (!$this->_status_id || !$this->_mail_id ||
                    empty($this->_status_id) || empty($this->_mail_id));
        } //isEmpty

        protected function BuildWhere() {
            $where = array();

            if( $this->_status_id ) $where[] = " StatusID=$this->_status_id";
            if( $this->_mail_id ) $where[] = " MaileID=$this->_mail_id";

            return implode(' AND ', $where);
        } //BuildWhere
*/
    } //class DBMailerSession

    //---------------------------------------------------------------------------------------------------

    class objDBMailer_Mailer extends objDBActiveRecord {
            protected $recordSession = false;
            protected $recordStatus = false;
            protected $recordMail = false;

            protected $_session = false;
            protected $_type = false;

            protected $_table = 'fa_mailer_mails';

        public function __construct() {
            parent::__construct();

            $this->MailerSession = '';
            $this->MailerStatus = '';
            $this->MailerMail = '';
        } //constructor

        public function ClassName() {
            return  __CLASS__;
        }//ClassName

        protected function Record() {
            $arr = $this->_db->GetActiveRecords($this->_table, $this->BuildWhere());
            adodb_pr($arr);
        } //Record

        public function __set($name, $value) {
            parent::__set($name, $value);
            switch(strtolower($name)) {
                case 'session':
                    $this->_session = $value;
                    $this->_sqls();
                    $this->Record();
                break;
                //-------------------------------------------------------------
                case 'type':
                    $this->_type = $value;
                    $this->_sqls();
                    $this->Record();
                break;
            } //switch
        } //setter

        public function __get($name) {
        } //getter

        public function Send() {
        } //Send

        public function getList($aSessionID=false) {
            if( $aSessionID ) $this->_session_id = $aSessionID;
            if( $this->_session_id ) {
            }//if SessionID set
        } //GetList

        protected function BuildWhere() {
            $where = array();

            $where[] = "COALESCE(status, 0)<>0";
            if( $this->_session ) $where[] = " SessionID=$this->_seesion";
            if( $this->_type ) $where[] = " Type=$this->_type";

            return implode(' AND ', $where);
        } //BuildWhere

        protected function _sqls() {
            parent::_sqls();
            //-----------------------------------------------------------------------------------
            $this->_sql_querys['not_close_sessions'] =
            " SELECT  " .
	            " ms.SessionID, " .
	            " ms.date as SessionDate, " .
	            " ms.CountMails, " .
	            " ( " .
	             " SELECT count(mm.MailID) " .
	             " FROM fa_mailer_mails mm " .
	             " WHERE mm.SessionID=ms.SessionID AND COALESCE(mm.StatusID, 0)=0 " .
	            " ) AS CountNotSent " .
            " FROM fa_mailer_sessions ms " .
            " WHERE   " .
	            " ( " .
	             " SELECT count(mm.MailID) " .
	             " FROM fa_mailer_mails mm " .
	             " WHERE mm.SessionID=ms.SessionID AND COALESCE(mm.StatusID, 0)<>0 " .
	            " ) = 0 " ;
            //-----------------------------------------------------------------------------------
            $this->_sql_querys['not_close_sessions'] = "";

        } //sqls

    } //class DBMailer_Mailer

    //---------------------------------------------------------------------------------------------------

//-------------------------------------------------------------------------------------------------------
?>
